﻿using System;
using System.Configuration;
using System.Data.Services.Client;
using System.Web.Security;

namespace WebPages.Account
{
    public partial class InitApp : System.Web.UI.Page
    {
        bool AdminExists(string adminName)
        {
            try
            {
                if (Membership.GetUser(adminName) == null) return false;
            }
            catch (DataServiceQueryException)
            {
                return false;
            }

            return true;
        }

        void CreateAdminUserIfnotExists()
        {
            var adminName = ConfigurationManager.AppSettings["AdminName"];

            if (AdminExists(adminName)) return;

            MembershipCreateStatus status;
            var user = Membership.CreateUser(
                adminName,
                ConfigurationManager.AppSettings["AdminPassword"],
                ConfigurationManager.AppSettings["AdminEmail"],
                ConfigurationManager.AppSettings["AdminQuestion"],
                ConfigurationManager.AppSettings["AdminAnswer"], true, null, out status);

            if (status != MembershipCreateStatus.Success || user == null) return;

            user.IsApproved = true;
            Membership.UpdateUser(user);
        }

        bool AdminsRoleExists(string adminsRoleName)
        {
            try
            {
                return Roles.RoleExists(adminsRoleName);
            }
            catch (DataServiceQueryException)
            {
                return false;
            }
        }

        void CreateAdminsRoleIfnotExists()
        {
            var adminsRoleName = ConfigurationManager.AppSettings["AdminRoleName"];
            if (AdminsRoleExists(adminsRoleName)) return;

            Roles.CreateRole(adminsRoleName);
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            CreateAdminUserIfnotExists();
            CreateAdminsRoleIfnotExists();
        }
    }
}